#include "nmea.h"
#include <stdint.h>
#include <time.h>
#include "rtklib.h"


struct nmea_buf_s
{
	char buf[512];
	int nbyte;
};

static struct nmea_buf_s nmea_buf = {"", 0};

int decode_nmea(char *buff, sol_t *sol);

static int begin_nmea(char *buff, unsigned char data)
{
    buff[0]=buff[1]; buff[1]=data;
    
    return (buff[0]=='$'&& buff[1]=='G') || buff[0]=='$'&& buff[1]=='B' || buff[0]=='$'&& buff[1]=='P';
}

static int end_nmea()
{
    return nmea_buf.buf[nmea_buf.nbyte - 2]==0x0d && nmea_buf.buf[nmea_buf.nbyte - 1]==0x0a;
}

static void crc_nmea(char *buf)
{
	char *q;
	char sum;
	for (q = buf + 1,sum = 0; *q != '*'; q++)
	{
		sum^=*q; /* check-sum */
	}

	q++;

	sprintf(q,"%02X%c%c%c", sum, 0x0D, 0x0A, 0x00);
}

time_t input_nmea(char data, unsigned char *p, int n)
{
	time_t nmea_time = 0;
    if(nmea_buf.nbyte==0) {
        if (!begin_nmea(nmea_buf.buf,data)) return 0;
        nmea_buf.nbyte=2;
        return 0;
    }
	else
	{
		if(data == '$')
		{
			nmea_buf.buf[1] = data;
			nmea_buf.nbyte = 0;
			return 0;
		}

		if(data != '\r' && data != '\n' && isprint((int)data) == 0)
		{
			nmea_buf.nbyte = 0;
			return 0;
		}

		if(nmea_buf.nbyte >= sizeof(nmea_buf.buf))
		{
			nmea_buf.nbyte = 0;
			return 0;
		}
		nmea_buf.buf[nmea_buf.nbyte++] = data;
		if(end_nmea())
		{
			nmea_buf.buf[nmea_buf.nbyte] = '\0';
			strncpy(p, nmea_buf.buf, n - 1);
			int crc;
			int ret = 0;
			if(ret > 0)
			{

#if 0
				switch(ptype)
				{
				case GPGGA:
					{
						nmeaGPGGA pkg;
						ret = nmea_parse_GPGGA(nmea_buf.buf, strlen(nmea_buf.buf), &pkg);
						if(ret == true)
						{
							double epoch[6];
							gtime_t t = timeget();
							time2epoch(t, epoch);
							epoch[3] = pkg.utc.hour;
							epoch[4] = pkg.utc.min;
							epoch[5] = pkg.utc.sec;
							gtime_t now = epoch2time(epoch);
							
							nmea_time = now.time;
						}
					}
					break;
#if 0
				case GPGSA:
					{
						nmeaGPGSA pkg;
						ret = nmea_parse_GPGSA(nmea_buf.buf, strlen(nmea_buf.buf), &pkg);
						if(ret == true)
						{
							nmea_GPGSA2info(&pkg, &nmea_info);
						}
					}
					break;
				case GPGSV:
					{
						nmeaGPGSV pkg;
						ret = nmea_parse_GPGSV(nmea_buf.buf, strlen(nmea_buf.buf), &pkg);
						if(ret == true)
						{
							nmea_GPGSV2info(&pkg, &nmea_info);
						}
					}
					break;
				case GPRMC:
					{
						nmeaGPRMC pkg;
						ret = nmea_parse_GPRMC(nmea_buf.buf, strlen(nmea_buf.buf), &pkg);
						if(ret == true)
						{
							nmea_GPRMC2info(&pkg, &nmea_info);
						}
					}
					break;
				case GPVTG:
					{
						nmeaGPVTG pkg;
						ret = nmea_parse_GPVTG(nmea_buf.buf, strlen(nmea_buf.buf), &pkg);
					}
					break;
				default:
					libg_log_debug("unsupport nmea type!\n");
					break;
#endif
				};
#endif
			}
			else
			{
			}
			
			nmea_buf.nbyte = 0;
		}

		return nmea_time;
	}
}